import os
import cv2
import requests
from pathlib import Path
from requests.exceptions import RequestException
from videofilesystem import build_video_queue  # 导入已有模块


#获取生成指定目录下的视频内容 并将其发送到指定位置
class VideoAPIUploader:
    """视频数据API上传器"""
    
    def __init__(self, root_dir, api_endpoint, timeout=30, max_retries=3):
        """
        初始化上传器
        
        :param root_dir: 视频根目录路径
        :param api_endpoint: 接口地址，如：http://host:port/path
        :param timeout: 请求超时时间(秒)
        :param max_retries: 最大重试次数
        """
        self.root_dir = Path(root_dir)
        self.api_endpoint = api_endpoint
        self.timeout = timeout
        self.max_retries = max_retries
        
        # 路径校验
        if not self.root_dir.exists():
            raise FileNotFoundError(f"根目录不存在: {root_dir}")
        if not self.root_dir.is_dir():
            raise NotADirectoryError(f"路径不是目录: {root_dir}")

    def execute_upload(self):
        """执行完整上传流程"""
        try:
            # 构建数据结构
            video_data = build_video_queue(str(self.root_dir))
            
            # 格式转换
            formatted_data = self._convert_to_api_format(video_data)
            
            # 发送请求
            return self._send_api_request(formatted_data)
            
        except Exception as e:
            return self._handle_error(e)

    def _convert_to_api_format(self, raw_data):
        """转换数据结构为API要求格式"""
        api_data = {"cameraList": []}
        
        for camera_path, queue_info in raw_data.items():
            camera_name = Path(camera_path).name
            camera_entry = {
                "name": camera_name,
                "svideoList": []
            }
            
            for video_info in queue_info['videos']:
                video_entry = {
                    # "camera_name": self._get_video_name(video_info['camera']),
                    # "video_name": self._get_video_name(video_info['video']),
                    "name": self._get_video_name(video_info['video_path']),
                    "duration": int(video_info['video_duration']),
                    "cover_path": video_info['cover_path']
                }
                camera_entry['svideoList'].append(video_entry)
            
            api_data['cameraList'].append(camera_entry)
        
        return api_data

    def _send_api_request(self, data):
        """发送API请求（包含重试机制）"""
        # 准备请求数据
        multipart_data, files = self._prepare_multipart(data)
        
        print("multipart_data: ",multipart_data)
        print("-------------------------------")
        # print("files: ", files)
        # 请求配置
        session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(max_retries=self.max_retries)
        session.mount('http://', adapter)
        session.mount('https://', adapter)
        
        try:
            response = session.post(
                self.api_endpoint,
                data=multipart_data,
                files=files,
                timeout=self.timeout
            )
            response.raise_for_status()
            return {
                "status": "success",
                "status_code": response.status_code,
                "data": response.json()
            }
        except RequestException as e:
            return self._handle_network_error(e)

    def _prepare_multipart(self, api_data):
        """构建multipart/form-data数据"""
        form_data = {}
        files = []
        
        for cam_idx, camera in enumerate(api_data['cameraList']):
            # 摄像头名称
            form_data[f'cameraList[{cam_idx}].name'] = camera['name']
            
            # 视频数据
            for vid_idx, video in enumerate(camera['svideoList']):
                prefix = f'cameraList[{cam_idx}].svideoList[{vid_idx}]'
                
                # 文本字段
                form_data[f'{prefix}.name'] = video['name']
                form_data[f'{prefix}.duration'] = str(video['duration'])
                
                # 文件字段
                with open(video['cover_path'], 'rb') as f:
                    files.append(
                        (f'{prefix}.file', (f.name, f.read(), 'image/jpeg'))
                    )
        
        return form_data, files

    # 工具方法
    @staticmethod
    def _get_video_name(video_path):
        """从路径提取视频名称（无扩展名）"""
        return Path(video_path).stem

    # 错误处理
    def _handle_error(self, error):
        """通用错误处理"""
        error_type = type(error).__name__
        return {
            "status": "error",
            "error_type": error_type,
            "message": str(error),
            "detail": f"处理失败于步骤：{self._get_error_step(error)}"
        }

    def _handle_network_error(self, error):
        """网络错误特殊处理"""
        err_info = {
            "status": "error",
            "error_type": "network_error",
            "message": str(error)
        }
        
        if hasattr(error, 'response'):
            response = error.response
            err_info.update({
                "status_code": response.status_code,
                "response_text": response.text[:200] if response.text else None
            })
        
        return err_info

    @staticmethod
    def _get_error_step(error):
        """判断错误发生阶段"""
        if isinstance(error, (FileNotFoundError, NotADirectoryError)):
            return "初始化阶段"
        elif 'cover_path' in str(error):
            return "封面文件处理"
        elif isinstance(error, requests.RequestException):
            return "API通信阶段"
        else:
            return "数据处理阶段"

# 使用示例
if __name__ == "__main__":
    # 初始化配置
    config = {
        "root_dir": "/data/mn4",
        "api_endpoint": "http://192.168.0.142:80/aiApi/aiSaveVideo",            
        "timeout": 45,
        "max_retries": 3
    }
    
    # 执行上传
    uploader = VideoAPIUploader(**config)
    result = uploader.execute_upload()
    
    # 处理结果
    if result['status'] == 'success':
        print("上传成功！响应数据：", result['data'])
    else:
        print(f"错误发生：{result['error_type']}")
        print("错误信息：", result['message'])
        if 'status_code' in result:
            print("HTTP状态码：", result['status_code'])



            
# if __name__ == "__main__":
#     processor = GIFUploadSystem()

#     image_dir = "/data/chunk_0000/chunk_0000_mp4/problem_cross"
#     output_dir = "/data/chunk_0000/chunk_0000_mp4/problem_cross_result/"
#     records = processor.create_gifs_with_records(
#         image_dir,
#         output_dir
#         )
#     # records = processor.create_gifs_with_records(
#     #     image_dir,
#     #     output_dir,
#     #     frames_per_gif=8,
#     #     resize_ratio=0.3
#     # )
#     # GIF_RECORD_FILE = "GIF_RECORD_FILE.json"
#     # # 保存记录文件
#     # with open(GIF_RECORD_FILE, 'w') as f:
#     #     json.dump(records, f, indent=2)

#     # 上传数据
#     upload_result = processor.upload_gifs(
#         gif_dir=output_dir,
#         api_url="http://192.168.0.142:80/aiApi/saveEvent",
#         camera_id="CAM01"
#           # 可指定或自动生成当前时间
#     )

